// 地区管理子组件 编辑与添加共用弹框
import React, { useEffect } from 'react';
import { Button, Upload, Modal, message, Form, Input, InputNumber } from 'antd';
import '../../../css/AddorRev.css'
import { addFreight, revFreight } from '../../../../api/opreationApi'

// 表格接口
interface DataType {
  key: React.Key
  freightId: number
  freightArea: string
  freightAmount: number
}

// 参数接口
interface PropsType {
  modalClose(): void,
  isModalOpen: boolean,
  head: string | null,
  nowRev: DataType | null
  getData(): void
}


export default function AddorRev(props: PropsType) {
  const [form] = Form.useForm();
  // 初始化
  useEffect(() => {
    //去修改form表单里面的默认值
    if (props.head === '添加区域') {
      form.setFieldsValue({
        freightArea: null,
        freightAmount: null,
      })
    } else {
      form.setFieldsValue({
        freightArea: props.nowRev?.freightArea,
        freightAmount: props.nowRev?.freightAmount,
      })
    }
  }, [props])

  // 对话框部分
  const handleOk = () => {
    props.modalClose()
  };

  const handleCancel = () => {
    props.modalClose()
  };
  // 表单部分
  const onFinish = (values: any) => {
    const data = {
      freightAmount: values.freightAmount,
      freightArea: values.freightArea
    }
    if (props.head === '添加区域') {
      addFreight(data).then(res => {
        props.getData()
      })
    } else {
      revFreight({ ...data, freightId: props.nowRev?.freightId }).then(res => {
        props.getData()
      })
    }
    props.modalClose()
    message.success('提交成功！')
  };

  return (
    <>
      <Modal title={props.head} open={props.isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
        >
          {/* 标题 */}
          <Form.Item
            label="地区"
            name="freightArea"
            rules={[{ required: true, message: '请输入地区！' }]}
            initialValue={props.nowRev?.freightArea}
          >
            <Input placeholder="请输入地区！" />
          </Form.Item>
          {/* 位置 */}
          <Form.Item
            label="运费"
            name="freightAmount"
            rules={[{ required: true, message: '请输入运费！' }]}
            initialValue={props.nowRev?.freightAmount}
          >
            <InputNumber placeholder="请输入运费！" />
          </Form.Item>
          {/* 操作按钮 */}
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} className='opreate'>
            <Button type="primary" htmlType="submit" className='submit'>提交</Button>
            <Button type="primary" onClick={handleCancel} className='cancel'>取消</Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
